package com.web;

import com.bean.User;
import com.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 页面跳转
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("user_username");
        String password = req.getParameter("user_password");

        try {
            // 创建对象并实现方法
            User user = new UserDao().get(username, password);

            // 判断用户不能为空
            if (user != null) {
                // 如果用户不为空，就把用户保存到 session 中
                req.getSession().setAttribute("user", user);
                req.getRequestDispatcher("/loginCG.jsp").forward(req, resp);
            } else {
                // 把失败的信息保存到 message 中
                req.setAttribute("message", "用户名或密码错误！");
                // 页面跳转
                req.getRequestDispatcher("/loginSB.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            // 把错误的信息打印到控制台
            e.printStackTrace();
            req.setAttribute("message", "登录失败！" + e.getLocalizedMessage());
            req.getRequestDispatcher("/loginSB.jsp").forward(req, resp);
        }
    }
}
